import 'dart:io';

import 'package:path_provider/path_provider.dart';

/// FileName cache_manager
///
/// @Author lax
/// @Date 2024/3/26
///
/// @Description

class CacheManager {
  /// 获取缓存目录
  static Future<Directory> cacheDirectory({bool temp = false}) async {
    Directory directory;
    if (temp) {
      directory = await getTemporaryDirectory();
    } else {
      directory = await getApplicationDocumentsDirectory();
    }
    return directory;
  }

  /// 获取缓存大小
  static Future<String?> allCacheSizeString() async {
    final size = await allCacheSize();
    return _sizeString(size: size);
  }

  static Future<String?> cacheSizeString({bool temp = false}) async {
    final size = await cacheSize(temp: temp);
    return _sizeString(size: size);
  }

  static String? _sizeString({int size = 0}) {
    if (size <= 0) {
      return null;
    }
    if (size < 1000 * 1000) {
      return '${size ~/ 1000}K';
    }
    return '${size ~/ 100000 / 10}M';
  }

  /// 获取缓存大小
  static Future<int> allCacheSize() async {
    var directory = await cacheDirectory(temp: true);
    var total = await _reduce(directory);
    directory = await cacheDirectory(temp: false);
    // total += await _reduce(directory);
    total = await _reduce(directory);
    return total;
  }

  static Future<int> cacheSize({bool temp = false}) async {
    final directory = await cacheDirectory(temp: temp);
    final total = await _reduce(directory);
    return total;
  }

  /// 清除缓存
  static Future<void> clearAll() async {
    var directory = await cacheDirectory(temp: true);
    // ios删除无权限
    // await _delete(directory);
    directory = await cacheDirectory(temp: false);
    await _delete(directory);
  }

  static Future<void> clear({bool temp = false}) async {
    final directory = await cacheDirectory(temp: temp);
    await _delete(directory);
  }

  /// 递归缓存目录，计算缓存大小
  static Future<int> _reduce(FileSystemEntity file) async {
    // 如果是一个文件，则直接返回文件大小
    if (file is File) {
      int length = await file.length();
      return length;
    }
    // 如果是目录，则遍历目录并累计大小
    if (file is Directory) {
      try {
        final List<FileSystemEntity> children = file.listSync();
        int total = 0;
        if (children.isNotEmpty) {
          for (final child in children) {
            total += await _reduce(child);
          }
        }
        return total;
      } catch (_) {
        return 0;
      }
    }
    return 0;
  }

  /// 递归删除缓存目录和文件
  static Future<void> _delete(FileSystemEntity file) async {
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      for (final child in children) {
        await _delete(child);
      }
    } else {
      await file.delete();
    }
  }
}
